package com.yeyks.commonReference.service.message.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeyks.account.dal.domain.AccountInfo;
import com.yeyks.common.appcommon.dto.AppMessageDTO;
import com.yeyks.common.appcommon.param.room.GetInRoomNoticeParam;
import com.yeyks.common.appcommon.result.CommonPage;
import com.yeyks.common.appcommon.result.CommonResult;
import com.yeyks.common.constants.MessageConst;
import com.yeyks.common.utils.apputil.bean.MyBeanUtils;
import com.yeyks.common.utils.apputil.type.AccountType;
import com.yeyks.common.utils.webutil.Utility;
import com.yeyks.config.dal.dao.MessageMapper;
import com.yeyks.config.dal.domain.Message;
import com.yeyks.commonReference.service.message.MessageService;
import com.yeyks.hotel.dal.dao.HotelInfoMapper;
import com.yeyks.hotel.dal.domain.HotelInfo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 消息推送表 服务实现类
 * </p>
 *
 * @author yun
 * @since 2019-06-25
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {
    private Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);

    @Autowired
    private HotelInfoMapper hotelInfoMapper;
    @Autowired
    MessageMapper messageMapper;

    public void passHotelInfo(HotelInfo hotelInfo) {
        try {
            Message msg = new Message();
            msg.setTitle(MessageConst.ENROLL_HOTEL);
            msg.setContent(String.format(MessageConst.ENROLL_HOTEL_CONTENT, hotelInfo.getName()));
            msg.setType(MessageConst.MT_ENROLL_HOTEL);
            msg.setToUserType("AB");
            if (messageMapper.insertReturnId(msg) == 0 || msg.getId() == 0) {
                throw new Exception("写入数据库异常");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }

        try {
            Message msg = new Message();
            msg.setTitle(MessageConst.PASS_HOTEL_USER);
            msg.setContent(String.format(MessageConst.PASS_HOTEL_USER_CONTENT, hotelInfo.getName()));
            msg.setType(MessageConst.MT_PASS_HOTEL_USER);
            msg.setToUserId(Integer.valueOf(hotelInfo.getAdminId()));
            if (messageMapper.insertReturnId(msg) == 0 || msg.getId() == 0) {
                throw new Exception("写入数据库异常");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    }

    public void nopassHotelInfo(HotelInfo hotelInfo) {
        try {
            Message msg = new Message();
            msg.setTitle(MessageConst.NOPASS_HOTEL_USER);
            msg.setContent(String.format(MessageConst.NOPASS_HOTEL_USER_CONTENT,
                    hotelInfo.getName(), Utility.getExtraInfo(hotelInfo.getExtraInfo(), "nopass_comment")));
            msg.setType(MessageConst.MT_NOPASS_HOTEL_USER);
            msg.setToUserId(Integer.valueOf(hotelInfo.getAdminId()));
            if (messageMapper.insertReturnId(msg) == 0 || msg.getId() == 0) {
                throw new Exception("写入数据库异常");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    }

    public void rejectRefund(Integer userId) {
        try {
            Message msg = new Message();
            msg.setTitle(MessageConst.REJECT_REFUND);
            msg.setContent(MessageConst.REJECT_REFUND_CONTENT);
            msg.setType(MessageConst.MT_NOPASS_HOTEL_USER);
            msg.setToUserId(Integer.valueOf(userId));
            if (messageMapper.insertReturnId(msg) == 0 || msg.getId() == 0) {
                throw new Exception("写入数据库异常");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    }

    public void msgToUser(Integer userId, String title, String content) {
        try {
            Message msg = new Message();
            msg.setTitle(title);
            msg.setContent(content);
            msg.setType(0);
            msg.setToUserId(Integer.valueOf(userId));
            if (messageMapper.insertReturnId(msg) == 0 || msg.getId() == 0) {
                throw new Exception("写入数据库异常");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    }

    public void createAccount(Long userId) {
        try {
            Message msg = new Message();
            msg.setTitle(MessageConst.CREATE_ACCOUNT);
            msg.setContent(MessageConst.CREATE_ACCOUNT_CONTENT);
            msg.setType(MessageConst.MT_CREATE_ACCOUNT);
            if(null!=userId) {
                msg.setToUserId(userId.intValue());
            }
            if (messageMapper.insertReturnId(msg) == 0 || msg.getId() == 0) {
                throw new Exception("写入数据库异常");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    }

    //======================admin -app 接口服务的实现 ===============

    @Override
    public CommonResult<CommonPage<AppMessageDTO>> getInRoomNotice(GetInRoomNoticeParam param, AccountInfo accountInfo) {

        CommonPage<AppMessageDTO> dtoCommonPage = new CommonPage<>();
        List<Message> appMessageList = Lists.newArrayList();
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        if (accountInfo.getType() == AccountType.USER) {
            return CommonResult.failed("没有权限查看入住通知");
        }else{
            appMessageList = messageMapper.selectByUserTypeList(null, "AB");
        }
        List<String> hotelNameList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(appMessageList)) {
            CommonPage<Message> messageCommonPage = CommonPage.restPage(param.getPageNum(), param.getLastId(), appMessageList);
            dtoCommonPage = MyBeanUtils.convertCommonPageList(messageCommonPage, AppMessageDTO.class);
            dtoCommonPage.getList().forEach(appMessageDTO -> {
                        appMessageDTO.setContextMessage("【" + appMessageDTO.getTitle() + "】" + appMessageDTO.getContent());
                        hotelNameList.add(appMessageDTO.getContent().substring(1, appMessageDTO.getContent().indexOf("”")));
                    }
            );
        }
        Map<String, HotelInfo> hotelInfoMap = Maps.newHashMap();
        if(!CollectionUtils.isEmpty(hotelNameList)){
            //查询酒店信息
            List<HotelInfo> hotelInfoList = hotelInfoMapper.selectList(new QueryWrapper<HotelInfo>().in(HotelInfo.NAME, hotelNameList));
            if(!CollectionUtils.isEmpty(hotelInfoList)){
                for(HotelInfo hotelInfo : hotelInfoList){
                    hotelInfoMap.put(hotelInfo.getName(), hotelInfo);
                }
            }
        }
        if(!CollectionUtils.isEmpty(hotelInfoMap)){
            dtoCommonPage.getList().forEach(appMessageDTO -> {
                        String hotelName = appMessageDTO.getContent().substring(1, appMessageDTO.getContent().indexOf("”"));
                        HotelInfo hotelInfo = hotelInfoMap.get(hotelName);
                        if(null != hotelInfo && hotelInfo.getId() != null){
                            appMessageDTO.setHotelId(hotelInfo.getId());
                        }
                    }
            );
        }
        return CommonResult.success(dtoCommonPage);
    }

}
